package com.googlecode.sc2dm.server.sender;

import com.googlecode.sc2dm.server.authentication.Authentication;
import com.googlecode.sc2dm.server.authentication.AuthenticationData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Author Jarle Hansen (jarle@jarlehansen.net)
 * Created: 2:09 PM - 9/28/11
 */
public class C2DMMessageSender implements MessageSender {
    private static final Logger logger = LoggerFactory.getLogger(C2DMMessageSender.class);
    private static final String c2dmUrl = "http://android.apis.google.com/c2dm/send";

    private final Authentication authentication;
    private final URL messageServiceUrl;

    public static MessageSender createMessageSender(AuthenticationData authenticationData) {
        return C2DMFactory.createMessageSender(authenticationData);
    }

    public C2DMMessageSender(Authentication authentication) {
        this.authentication = authentication;

        try {
            messageServiceUrl = new URL(c2dmUrl);
        } catch (MalformedURLException mal) {
            throw new IllegalStateException(mal);
        }
    }


    public boolean sendMessage(MessageData... messages) {
        String token = authentication.getAuthToken();

        boolean msgSent;
        try {
            for (MessageData message : messages) {
                String content = message.createMessageString();
                logger.info("Sending: " + content);

                HttpURLConnection connection = (HttpURLConnection) messageServiceUrl.openConnection();

                connection.setDoOutput(true);
                connection.setUseCaches(false);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                connection.setRequestProperty("Content-Length", Integer.toString(content.length()));
                connection.setRequestProperty("Authorization", "GoogleLogin auth=" + token);

                OutputStream out = connection.getOutputStream();
                out.write(content.getBytes("UTF-8"));
                out.close();

                logger.info("Response: " + connection.getResponseCode());

                // Check for updated token header
                String updatedAuthToken = connection.getHeaderField("Update-Client-Auth");
                if (updatedAuthToken != null && !token.equals(updatedAuthToken)) {
                    logger.warn("Got updated auth token from C2DM servers: " + updatedAuthToken);
                    logger.warn("Persisting updated token, please try to push message again");
                }
            }

            msgSent = true;
        } catch (IOException e) {
            e.printStackTrace();
            msgSent = false;
        }

        return msgSent;
    }
}
